﻿

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text.RegularExpressions;
using Domain.Entidades;
using Domain.Interfaces.Repositorios;
using Domain.Interfaces.Servicos;


namespace Domain.Servicos
{
    public class AvisoService : ServiceBase<aviso>, IAvisoService
    {
        private readonly IAvisoRepository _avisoRepository;
        private readonly IUsuarioService _usuarioservice;


        public AvisoService(IAvisoRepository avisoRepository,IUsuarioService usuarioservice) : base(avisoRepository)
        {
            _avisoRepository= avisoRepository;
            _usuarioservice= usuarioservice;
        }

        public void enviar_email(aviso aviso, VW_usuarios user)
        {
            try
            {
                
                List<VW_usuarios> user_email = new List<VW_usuarios>();

                if (aviso.tipo == "uni")
                {

                    foreach (string uni in aviso.tipos)
                    {

                        int u = int.Parse(uni);
                        List<VW_usuarios> aux;
                        aux = _usuarioservice.busca_usuarios_setor_unidade(1, u).ToList();
                        user_email.AddRange(aux);


                    }
                }

                else
                {

                    foreach (string set in aviso.tipos)
                    {

                        int s = int.Parse(set);
                        List<VW_usuarios> aux;
                        aux = _usuarioservice.busca_usuarios_setor_unidade(2, s).ToList();
                        user_email.AddRange(aux);


                    }


                }
                user_email = user_email.Where(x => x.sta_codigo == 1).ToList();


                String cCorpoEmail = "";


                System.Net.Mail.MailMessage objNovoEmail = new System.Net.Mail.MailMessage();
                SmtpClient objSmtp = new SmtpClient();


                foreach (VW_usuarios usu in user_email)
                {

                    if (usu.usu_email!=null)
                    {
                 

                    if (usu.usu_email.IndexOf('@') < 0)
                    {

                        objNovoEmail.To.Add(new MailAddress(usu.usu_email + "@credivale.org.br"));
                    }
                    else
                    {
                        objNovoEmail.To.Add(new MailAddress(usu.usu_email));
                    }

                }
                }

                VW_usuarios obj= _usuarioservice.GetUsuarioLogado(0);


                objNovoEmail.From = new MailAddress(obj.usu_email + "@credivale.org.br");


                //Adiciona a prioridade do e-mail
                objNovoEmail.Priority = System.Net.Mail.MailPriority.High;

                //                // 'Adicionando o assunto ao atributo assunto
                objNovoEmail.Subject = "SICOOBCREDIVALE - AVISO IMPORTANTE";

                //                // 'Formato de e-mail em Html?
                objNovoEmail.IsBodyHtml = true;


                cCorpoEmail = "<html><head><meta charset='utf-8' /></head><body>" +
                              "<table style='border-color:#003b42; border-radius: 15px; font-family:Arial, Geneva, sans-serif;' cellspacing='0' cellpadding='30' width='800px' border='4' align='center'><tr><td>" +
                              "<div style='overflow: hidden; margin-left:auto; margin-right:auto;" +
                              " margin-top:15px; padding-bottom:10px; border-bottom: 5px solid #CCC; width:800px; float:none; text-align:center;'>" +
                              "<font style='font-size:40px;  font-weight:bold; color:#00494e'>SICOOB</font><font style='font-size:40px;  font-weight:bold; color:#00b0a0'>CREDIVALE</font><br/><br/>" +
                              " <font style='font-size:20px;  font-weight:bold; '>Aviso registrado na Intranet</font><br/><br/>" +
                              "<font style='font-size:15px; font-weight:bold; float:left;'>Por: </font>" + user.usu_nome + " - " + user.usu_login + "(" + user.set_descricao + ")<br/> " +
                              "<font style='font-size:15px; font-weight:bold; float:left;'>Em: </font>" + String.Format("{0:dd/MM/yyyy HH:mm}", aviso.aviso_data) + "</div><br/><br/>" +
                              "<div style='overflow: hidden; padding: 17px; margin-left:auto; margin-right:auto;" +
                              "margin-bottom:10px;  width:800px;float:none; text-align:LEFT;'>" +
                              aviso.aviso_descricao +
                              "</div></td></tr></table></body></html>";




                objNovoEmail.Body = cCorpoEmail;

            
                 objNovoEmail.BodyEncoding= System.Text.Encoding.GetEncoding("UTF-8");

              
                objSmtp.Host = "smtp.credivale.org.br";
                objSmtp.Port = 587;

          
                objSmtp.Credentials = new System.Net.NetworkCredential(obj.usu_email + "@credivale.org.br", obj.usu_senhaemail);
             
           
                objSmtp.Send(objNovoEmail);
                objNovoEmail.Dispose();


            }
            catch (Exception ex)
            {
                throw new Exception("email" + ex.Message);

            }
           
        }
        public IEnumerable<VW_avisos> Listar(DateTime dt1,DateTime dt2,VW_usuarios usuario)
        {

       
            try
            {
                IEnumerable<VW_avisos> avisos = _avisoRepository.Listar(dt1, dt2, usuario);
                     foreach (VW_avisos av in avisos)
                {
                    av.desc_html = Regex.Replace(av.aviso_descricao, "<[^>]*>", " ");

                }

                return avisos;

            }
            catch (Exception ex)
            {
                
                throw ex;
            }


        }
        public void Inserir(aviso aviso)
        {

            try
            {
                VW_usuarios user = _usuarioservice.GetUsuarioLogado(0);
                _avisoRepository.Inserir(aviso,user.usu_codigo);
                enviar_email(aviso,user);
            }


            catch (Exception ex)
            {

                throw ex;
            }



        }
        public VW_avisos carrega_aviso(int codigo)
        {

            try
            {



                return _avisoRepository.carrega_aviso(codigo);


            }
            catch (Exception ex)
            {

                throw ex;
            }


        }
        public void deletar(aviso aviso)
        {
            try
            {
                   _avisoRepository.deletar(aviso,_usuarioservice.GetUsuarioLogado(0).usu_codigo);
            }
            catch (Exception ex)
            {
                

                throw ex;
            }

        }
        public aviso GetId(int codigo)
        {
            try
            {
               return _avisoRepository.GetId(codigo);
            }
            catch (Exception ex)
            {


                throw ex;
            }

        }



    }
}
